package com.quanxiaoha.xiaohashu.data.align.job;


import cn.hutool.core.collection.CollUtil;
import com.quanxiaoha.xiaohashu.data.align.constant.RedisKeyConstants;
import com.quanxiaoha.xiaohashu.data.align.constant.TableConstants;
import com.quanxiaoha.xiaohashu.data.align.domain.mapper.DeleteMapper;
import com.quanxiaoha.xiaohashu.data.align.domain.mapper.SelectMapper;
import com.quanxiaoha.xiaohashu.data.align.domain.mapper.UpdateMapper;
import com.quanxiaoha.xiaohashu.data.align.model.dto.CollectUnCollectNoteMqDTO;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@Slf4j
public class FollowingCountShardingXxlJob {
    @Resource
    private SelectMapper selectMapper;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private UpdateMapper updateMapper;

    @Resource
    private DeleteMapper deleteMapper;


    @XxlJob("followingCountShardingJobHandler")
    public void followingCountShardingJobHandler() throws Exception {
        //获取分片参数
        //分片序号
        int shardIndex = XxlJobHelper.getShardIndex();
        //分片总数
        int shardTotal = XxlJobHelper.getShardTotal();
        XxlJobHelper.log("分片参数：当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);

        log.info("分片参数：当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);
        //表后缀,去对其昨天的数据
        String date = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        //表名后缀
        String tableNameSuffix = TableConstants.buildTableNameSuffix(date, shardIndex);

        //一批次1000条
        int batchSize = 1000;
        //共对其了多少条记录，默认为0
        int processedTotal = 0;
        for(;;){
            List<Long> userIds = selectMapper.selectBatchFromDataAlignFollowingCountTempTable(tableNameSuffix, batchSize);

            //若记录为空，终止循环
            if(CollUtil.isEmpty(userIds)) break;

            userIds.forEach(userId -> {
                int followingTotal = selectMapper.selectCountFromFollowingTableByUserId(userId);
                int count = updateMapper.updateUserFollowingTotalByUserId(userId, followingTotal);

                if(count>0){
                    String redisKey = RedisKeyConstants.buildCountUserKey(userId);
                    //判断Hash是否存在
                    boolean hashKey = redisTemplate.hasKey(redisKey);

                    // 若存在
                    if (hashKey) {
                        // 更新 Hash 中的 Field 关注总数
                        redisTemplate.opsForHash().put(redisKey, RedisKeyConstants.FIELD_FOLLOWING_TOTAL, followingTotal);
                    }
                }

                // TODO: 3: 更新 t_user_count 表, 更新对应 Redis 缓存
            });
            // TODO: 4. 批量物理删除这一批次记录
            deleteMapper.batchDeleteDataAlignFollowingCountTempTable(tableNameSuffix, userIds);

            // 当前已处理的记录数
            processedTotal += userIds.size();
        }

    }
}
